/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { FileSet, hvigorCore, TaskInputValue } from '@ohos/hvigor';
import { generateUnitTestTemplate } from '@ohos/hvigor-arkts-compose';

import { CommonConst } from '../../const/common-const';
import { ProjectModelImpl } from '../../model/project/project-model-impl.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosModuleTask } from '../task/ohos-module-task.js';

type GenerateUnitTestTemplateParams = Parameters<typeof generateUnitTestTemplate>[0];

/**
 * 不依赖DevEco Studio的单元测试构建任务的前置任务
 *
 * @since 2023/12/19
 */
export class GenerateUnitTestTemplate extends OhosModuleTask {
  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.Task.GENERATE_UNIT_TEST_TEMPLATE);
  }

  private getParams(): GenerateUnitTestTemplateParams {
    const config = hvigorCore.getExtraConfig();
    const appRes = (this.projectModel as ProjectModelImpl).getAppRes().getAppResOpt();
    return {
      bundleName: appRes.app.bundleName,
      moduleName: this.moduleName,
      scope: config.get(CommonConst.OHOS_TEST_COVERAGE_SCOPE),
      coverage: config.get(CommonConst.OHOS_TEST_COVERAGE) === 'true',
      modulePath: this.pathInfo.getModulePath(),
    };
  }

  declareOutputFiles(): FileSet {
    const fileSet = super.declareOutputFiles();
    fileSet.addEntry(this.pathInfo.getUnitTestTemplatePath(), { isDirectory: true });
    return fileSet;
  }

  declareInputs(): Map<string, TaskInputValue> {
    const map = super.declareInputs();
    const params = this.getParams();

    (Object.keys(params) as Array<keyof typeof params>).forEach((key) => {
      const value = params[key];

      if (typeof value !== 'undefined') {
        map.set(key, value);
      }
    });

    return map;
  }

  async doTaskAction() {
    generateUnitTestTemplate(this.getParams());
  }

  initTaskDepends() {
    // do nothing
  }
}
